<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { addApp, listMyAppVoByPage, listGoodAppVoByPage } from '@/api/appController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { SearchOutlined, SendOutlined, PaperClipOutlined, ThunderboltOutlined, ArrowUpOutlined } from '@ant-design/icons-vue'
import { CODE_GEN_TYPE } from '@/constants/codeGenType'
import { getDeployUrl } from '@/config/env'
import AppCard from '@/components/AppCard.vue'
import EmptyState from '@/components/EmptyState.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 提示词输入
const promptInput = ref('')
const createLoading = ref(false)

// 文件上传相关
const uploadVisible = ref(false)
const uploadLoading = ref(false)

// 优化功能相关
const optimizeLoading = ref(false)

// 标签相关
const selectedTags = ref<string[]>([])
const defaultTags = [
  // 应用类型
  '网站', '工具', '游戏', '教育', '商务', '博客', '电商', '社交',
  // 技术栈
  'HTML', 'CSS', 'JavaScript', 'Vue', 'React', 'TypeScript',
  // 风格
  '简约', '现代', '创意', '专业', '可爱', '商务风',
  // 功能
  '管理系统', 'Landing Page', '移动端', '响应式', '交互式'
]

// 我的应用列表
const myApps = ref<API.AppVO[]>([])
const myAppsLoading = ref(false)
const myAppsPagination = reactive({
  pageNum: 1,
  pageSize: 8,
  total: 0
})

// 精选应用列表
const goodApps = ref<API.AppVO[]>([])
const goodAppsLoading = ref(false)
const goodAppsPagination = reactive({
  pageNum: 1,
  pageSize: 8,
  total: 0
})

// 搜索参数
const myAppsSearchParams = reactive({
  appName: '',
  tags: [] as string[]
})
const goodAppsSearchParams = reactive({
  appName: '',
  tags: [] as string[]
})

// 精选案例标签分类
const categoryTabs = [
  { key: 'all', label: '全部', tags: [] },
  { key: 'website', label: '网站应用', tags: ['网站', 'Landing Page', '博客', '简约', '现代'] },
  { key: 'tool', label: '实用工具', tags: ['工具', 'JavaScript', '实用', '计算'] },
  { key: 'game', label: '游戏娱乐', tags: ['游戏', '交互式', '创意', '娱乐'] },
  { key: 'business', label: '商务管理', tags: ['管理系统', '商务', '专业', 'Vue'] },
  { key: 'showcase', label: '技术展示', tags: ['Vue', 'React', 'HTML', 'CSS', 'TypeScript'] }
]

// 当前选中的分类
const activeCategoryTab = ref('all')

/**
 * 创建应用
 * 用户输入提示词后，调用后端接口创建应用，然后跳转到对话页面
 */
const handleCreateApp = async () => {
  if (!promptInput.value.trim()) {
    message.error('请输入应用描述')
    return
  }

  if (!loginUserStore.loginUser.id) {
    message.error('请先登录')
    loginUserStore.openLoginModal()
    return
  }

  createLoading.value = true
  try {
    const res = await addApp({
      initPrompt: promptInput.value.trim(),
      codeGenType: CODE_GEN_TYPE.MULTI_FILE, // 使用枚举常量
      tags: selectedTags.value.length > 0 ? selectedTags.value : undefined
    })

    if (res.data.code === 0 && res.data.data) {
      const appId = res.data.data
      const prompt = promptInput.value.trim()

      message.success('应用创建成功，正在初始化...')

      // 保存新应用标记和初始提示词到sessionStorage
      sessionStorage.setItem(`newApp_${appId}`, 'true')
      sessionStorage.setItem(`initPrompt_${appId}`, prompt)

      // 清空输入框和标签
      promptInput.value = ''
      selectedTags.value = []

      // 立即跳转，让对话页面处理初始化
      router.push(`/app/chat/${appId}`)
    } else {
      message.error('创建失败：' + res.data.message)
    }
  } catch (error) {
    message.error('创建失败，请检查网络连接')
  } finally {
    createLoading.value = false
  }
}

/**
 * 处理文件上传
 */
const handleFileUpload = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.txt,.md,.doc,.docx,.rtf'
  input.style.display = 'none'

  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (!file) return

    uploadLoading.value = true

    try {
      const text = await readFileAsText(file)
      if (text.trim()) {
        // 将文件内容设置为提示词输入
        promptInput.value = text.trim()
        message.success('文件内容已读取成功')
      } else {
        message.error('文件内容为空')
      }
    } catch (error) {
      message.error('文件读取失败：' + (error as Error).message)
    } finally {
      uploadLoading.value = false
      // 清理DOM元素
      document.body.removeChild(input)
    }
  }

  // 添加到DOM并触发点击
  document.body.appendChild(input)
  input.click()
}

/**
 * 读取文件内容为文本
 */
const readFileAsText = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e) => {
      const result = e.target?.result
      if (typeof result === 'string') {
        resolve(result)
      } else {
        reject(new Error('无法读取文件内容'))
      }
    }

    reader.onerror = () => {
      reject(new Error('文件读取出错'))
    }

    // 检查文件大小（限制为1MB）
    if (file.size > 1024 * 1024) {
      reject(new Error('文件大小不能超过1MB'))
      return
    }

    reader.readAsText(file, 'utf-8')
  })
}

/**
 * 优化提示词内容
 */
const handleOptimizePrompt = async () => {
  if (!promptInput.value.trim()) {
    message.error('请先输入内容再进行优化')
    return
  }

  optimizeLoading.value = true

  try {
    // 简单的提示词优化逻辑
    const optimizedPrompt = optimizePromptText(promptInput.value.trim())
    promptInput.value = optimizedPrompt
    message.success('内容优化完成')
  } catch (error) {
    message.error('优化失败：' + (error as Error).message)
  } finally {
    optimizeLoading.value = false
  }
}

/**
 * 优化提示词文本
 */
const optimizePromptText = (text: string): string => {
  let optimized = text.trim()

  // 1. 如果文本太简单，添加明确的目标说明
  if (optimized.length < 10) {
    optimized = `请创建一个关于${optimized}的现代化网站`
  }

  // 2. 检查是否明确了项目类型，如果没有则添加
  if (!optimized.includes('网站') && !optimized.includes('应用') && !optimized.includes('页面') && !optimized.includes('系统')) {
    optimized = optimized + '网站'
  }

  // 3. 添加设计要求
  if (!optimized.includes('界面') && !optimized.includes('设计') && !optimized.includes('美观')) {
    optimized += '，界面设计要现代美观'
  }

  // 4. 添加功能完整性要求
  if (!optimized.includes('功能') && !optimized.includes('完整')) {
    optimized += '，功能要完整实用'
  }

  // 5. 添加技术特性
  if (!optimized.includes('响应式') && !optimized.includes('适配')) {
    optimized += '，支持响应式布局适配不同设备'
  }

  // 6. 添加用户体验要求
  if (!optimized.includes('体验') && !optimized.includes('交互') && !optimized.includes('易用')) {
    optimized += '，注重用户体验和交互效果'
  }

  // 7. 确保语句流畅
  optimized = optimized
    .replace(/，，+/g, '，') // 去除重复逗号
    .replace(/，$/, '') // 去除末尾逗号

  return optimized
}

/**
 * 根据提示词自动推荐标签
 */
const autoSuggestTags = (prompt: string): string[] => {
  const lowerPrompt = prompt.toLowerCase()
  const suggestedTags: string[] = []

  // 根据关键词匹配推荐标签
  const tagRules = [
    { keywords: ['vue', 'vue.js', 'vue项目'], tags: ['Vue', '网站', '现代'] },
    { keywords: ['react', 'react.js'], tags: ['React', '网站', '现代'] },
    { keywords: ['html', '单页面', '静态'], tags: ['HTML', '网站', '简约'] },
    { keywords: ['管理系统', '后台', '管理'], tags: ['管理系统', 'Vue', '专业'] },
    { keywords: ['博客', '文章', '内容'], tags: ['博客', '网站', '现代'] },
    { keywords: ['游戏', '互动', '娱乐'], tags: ['游戏', '交互式', '创意'] },
    { keywords: ['工具', '计算', '生成'], tags: ['工具', 'JavaScript', '实用'] },
    { keywords: ['电商', '购物', '商城'], tags: ['电商', '商务', '现代'] },
    { keywords: ['简历', '个人', '展示'], tags: ['简约', 'HTML', '专业'] },
    { keywords: ['落地页', 'landing', '产品'], tags: ['Landing Page', '营销', '现代'] },
    { keywords: ['响应式', '移动', '适配'], tags: ['响应式', '移动端', '现代'] }
  ]

  tagRules.forEach(rule => {
    if (rule.keywords.some(keyword => lowerPrompt.includes(keyword))) {
      suggestedTags.push(...rule.tags)
    }
  })

  // 去重并限制数量
  return [...new Set(suggestedTags)].slice(0, 4)
}

/**
 * 当提示词改变时自动计算标签（节流处理，不显示给用户）
 */
let promptChangeTimer: NodeJS.Timeout | null = null
const handlePromptChange = () => {
  if (promptChangeTimer) {
    clearTimeout(promptChangeTimer)
  }
  promptChangeTimer = setTimeout(() => {
    if (promptInput.value.trim().length > 5) {
      // 自动计算标签但不显示给用户，在创建时使用
      const suggested = autoSuggestTags(promptInput.value)
      selectedTags.value = suggested.slice(0, 4) // 限制为4个，静默设置
    } else {
      selectedTags.value = [] // 清空自动标签
    }
  }, 500) // 500ms节流
}


/**
 * 获取我的应用列表
 */
const fetchMyApps = async () => {
  if (!loginUserStore.loginUser.id) return

  myAppsLoading.value = true
  try {
    const res = await listMyAppVoByPage({
      pageNum: myAppsPagination.pageNum,
      pageSize: myAppsPagination.pageSize,
      appName: myAppsSearchParams.appName || undefined,
      tags: myAppsSearchParams.tags.length > 0 ? myAppsSearchParams.tags : undefined,
      sortField: 'createTime',  // 🔧 按创建时间排序
      sortOrder: 'desc'         // 🔧 倒序排列，最新的在前面
    })

    console.log('我的应用列表响应:', res)

    if (res.data.code === 0 && res.data.data) {
      myApps.value = res.data.data.records || []
      myAppsPagination.total = res.data.data.totalRow || 0
      console.log('我的应用列表加载成功:', myApps.value)
      console.log('第一个应用:', myApps.value[0])
    } else {
      message.error('获取我的应用失败：' + res.data.message)
    }
  } catch (error) {
    message.error('获取我的应用失败，请检查网络连接')
  } finally {
    myAppsLoading.value = false
  }
}

/**
 * 获取精选应用列表
 */
const fetchGoodApps = async () => {
  goodAppsLoading.value = true
  try {
    const res = await listGoodAppVoByPage({
      pageNum: goodAppsPagination.pageNum,
      pageSize: goodAppsPagination.pageSize,
      appName: goodAppsSearchParams.appName || undefined,
      tags: goodAppsSearchParams.tags.length > 0 ? goodAppsSearchParams.tags : undefined,
      sortField: 'createTime',  // 🔧 按创建时间排序
      sortOrder: 'desc'         // 🔧 倒序排列，最新的在前面
    })

    console.log('精选应用列表响应:', res)

    if (res.data.code === 0 && res.data.data) {
      goodApps.value = res.data.data.records || []
      goodAppsPagination.total = res.data.data.totalRow || 0
      console.log('精选应用列表加载成功:', goodApps.value)
      console.log('第一个精选应用:', goodApps.value[0])
    } else {
      message.error('获取精选应用失败：' + res.data.message)
    }
  } catch (error) {
    message.error('获取精选应用失败，请检查网络连接')
  } finally {
    goodAppsLoading.value = false
  }
}

/**
 * 搜索我的应用
 */
const searchMyApps = () => {
  myAppsPagination.pageNum = 1
  fetchMyApps()
}

/**
 * 搜索精选应用
 */
const searchGoodApps = () => {
  goodAppsPagination.pageNum = 1
  fetchGoodApps()
}

/**
 * 我的应用分页变化
 */
const handleMyAppsPageChange = (page: number, pageSize: number) => {
  myAppsPagination.pageNum = page
  myAppsPagination.pageSize = pageSize
  fetchMyApps()
}

/**
 * 精选应用分页变化
 */
const handleGoodAppsPageChange = (page: number, pageSize: number) => {
  goodAppsPagination.pageNum = page
  goodAppsPagination.pageSize = pageSize
  fetchGoodApps()
}

/**
 * 切换精选案例分类
 */
const handleCategoryTabChange = (categoryKey: string) => {
  // 如果点击的是当前激活的tab，不重复请求
  if (activeCategoryTab.value === categoryKey) {
    return
  }

  activeCategoryTab.value = categoryKey
  
  // 根据选中的分类设置标签筛选
  const selectedCategory = categoryTabs.find(tab => tab.key === categoryKey)
  if (selectedCategory) {
    goodAppsSearchParams.tags = selectedCategory.tags
    goodAppsPagination.pageNum = 1 // 重置到第一页
    fetchGoodApps()
  }
}

/**
 * 查看应用详情
 */
const viewAppDetail = (app: API.AppVO) => {
  console.log('点击查看应用详情, app:', app)

  if (!app || !app.id) {
    message.error('应用信息不存在')
    console.error('应用数据不存在:', app)
    return
  }

  const detailUrl = `/app/detail/${app.id}`
  console.log('跳转到:', detailUrl)
  router.push(detailUrl)
}

/**
 * 查看作品 - 打开部署的应用
 */
const viewWork = (app: API.AppVO) => {
  console.log('点击查看作品, app:', app)
  if (!app.deployKey) {
    message.error('该应用尚未部署')
    return
  }

  // 部署地址
  const deployUrl = getDeployUrl(app.deployKey)
  console.log('打开部署地址:', deployUrl)

  // 在新标签页打开
  window.open(deployUrl, '_blank')
}

/**
 * 进入对话页面
 * @param app 应用信息
 * @param isViewMode 是否为查看模式（不自动发送消息）
 */
const enterChat = (app: API.AppVO, isViewMode = false) => {
  console.log('点击进入对话, app:', app, 'isViewMode:', isViewMode)

  if (!app || !app.id) {
    message.error('应用信息不存在')
    console.error('应用数据不存在:', app)
    return
  }

  const chatUrl = isViewMode ? `/app/chat/${app.id}?view=1` : `/app/chat/${app.id}`
  console.log('跳转到:', chatUrl)
  router.push(chatUrl)
}

// 页面加载时获取数据
onMounted(() => {
  fetchGoodApps()
  if (loginUserStore.loginUser.id) {
    fetchMyApps()
  }
})
</script>

<template>
  <div class="home-page">
    <!-- 网站标题和介绍 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">
          <span class="title-gradient">一句话</span>
          <span class="title-accent">✨</span>
          <span class="title-gradient">呈所想</span>
        </h1>
        <p class="hero-subtitle">与 AI 对话，让创意变成现实</p>

        <!-- 聊天输入框 -->
        <div class="chat-input-section">
          <div class="chat-container">
            <a-textarea
              v-model:value="promptInput"
              placeholder="输入你的想法，创建一个精美的网站"
              :disabled="createLoading"
              :auto-size="{ minRows: 3, maxRows: 8 }"
              class="chat-textarea"
              @input="handlePromptChange"
            />
            <div class="input-actions">
              <div class="action-buttons">
                <a-tooltip title="上传文档文件，自动读取内容作为需求描述" placement="top">
                  <a-button
                    type="text"
                    class="action-btn upload-btn"
                    :disabled="createLoading || uploadLoading"
                    :loading="uploadLoading"
                    @click="handleFileUpload"
                  >
                    <template #icon><PaperClipOutlined /></template>
                    上传
                  </a-button>
                </a-tooltip>
                <a-tooltip title="智能优化描述内容，让AI更好理解您的需求" placement="top">
                  <a-button
                    type="text"
                    class="action-btn optimize-btn"
                    :disabled="createLoading || optimizeLoading || !promptInput.trim()"
                    :loading="optimizeLoading"
                    @click="handleOptimizePrompt"
                  >
                    <template #icon><ThunderboltOutlined /></template>
                    优化
                  </a-button>
                </a-tooltip>
              </div>
              <a-button
                type="primary"
                :loading="createLoading"
                @click="handleCreateApp"
                :disabled="!promptInput.trim()"
                class="send-button"
              >
                <template #icon><ArrowUpOutlined /></template>
              </a-button>
            </div>
          </div>

          <!-- 隐藏标签选择器，但保留自动计算功能 -->

          <!-- 示例提示 -->
          <div class="example-prompts">
            <span class="example-label">试试这些：</span>
            <a-tag @click="promptInput = '创建一个精美的产品落地页，包含产品介绍、特性展示、用户评价区域，使用渐变背景和滚动动效，单页面HTML实现'" class="example-tag">产品落地页</a-tag>
            <a-tag @click="promptInput = '开发一个互动式的井字棋游戏，包含双人对战、得分统计，使用HTML、CSS、JavaScript三文件结构'" class="example-tag">井字棋游戏</a-tag>
            <a-tag @click="promptInput = '构建一个现代化的任务管理系统，支持任务增删改查、分类标签、进度跟踪、数据本地存储，使用Vue框架开发'" class="example-tag">任务管理</a-tag>
            <a-tag @click="promptInput = '设计一个创意十足的个人简历页面，包含技能雷达图、项目时间线、联系表单，使用纯HTML实现，简洁优雅'" class="example-tag">个人简历</a-tag>
            <a-tag @click="promptInput = '制作一个实用的密码生成器工具，支持自定义长度、字符类型、强度检测、一键复制，使用HTML+CSS+JS实现'" class="example-tag">密码生成器</a-tag>
            <a-tag @click="promptInput = '打造一个完整的博客管理平台，包含文章发布、分类管理、评论系统、搜索功能、用户认证，使用Vue全家桶开发'" class="example-tag">博客平台</a-tag>
          </div>

          <!-- 功能说明 -->
          <div class="feature-tips">
            <div class="tip-item">
              <PaperClipOutlined class="tip-icon" />
              <span>支持上传 .txt、.md、.doc 等文档</span>
            </div>
            <div class="tip-item">
              <ThunderboltOutlined class="tip-icon" />
              <span>智能优化描述，提升AI理解效果</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的作品 -->
    <div v-if="loginUserStore.loginUser.id" class="section my-apps-section">
      <div class="section-header">
        <h2 class="section-title">我的作品</h2>
        <div class="section-actions">
          <a-select
            v-model:value="myAppsSearchParams.tags"
            mode="multiple"
            placeholder="按标签筛选"
            style="width: 160px; margin-right: 12px"
            :options="defaultTags.map(tag => ({ label: tag, value: tag }))"
            allow-clear
            @change="searchMyApps"
            size="small"
          />
          <a-input-search
            v-model:value="myAppsSearchParams.appName"
            placeholder="搜索我的应用"
            @search="searchMyApps"
            style="width: 200px"
          />
        </div>
      </div>

      <a-spin :spinning="myAppsLoading">
        <div class="apps-grid">
          <AppCard
            v-for="app in myApps"
            :key="app.id"
            :app="app"
            :show-author="false"
            :show-chat-button="true"
            @click="viewAppDetail"
            @chat="(app) => enterChat(app, false)"
            @detail="viewAppDetail"
            @view-work="viewWork"
          />
        </div>

        <EmptyState
          v-if="myApps.length === 0 && !myAppsLoading"
          description="暂无应用，快去创建一个吧！"
        />

        <a-pagination
          v-if="myAppsPagination.total > 0"
          :current="myAppsPagination.pageNum"
          :page-size="myAppsPagination.pageSize"
          :total="myAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="false"
          @change="handleMyAppsPageChange"
          class="pagination"
        />
      </a-spin>
    </div>

    <!-- 精选案例 -->
    <div class="section good-apps-section">
      <div class="section-header">
        <h2 class="section-title">精选案例</h2>
        <div class="section-actions">
          <a-input-search
            v-model:value="goodAppsSearchParams.appName"
            placeholder="搜索精选应用"
            @search="searchGoodApps"
            style="width: 200px"
          />
        </div>
      </div>

      <!-- 分类标签页 -->
      <div class="category-tabs">
        <div class="tabs-container">
          <div 
            v-for="tab in categoryTabs" 
            :key="tab.key"
            :class="['tab-item', { 
              active: activeCategoryTab === tab.key,
              loading: goodAppsLoading && activeCategoryTab === tab.key
            }]"
            @click="handleCategoryTabChange(tab.key)"
          >
            {{ tab.label }}
            <a-spin v-if="goodAppsLoading && activeCategoryTab === tab.key" size="small" style="margin-left: 8px" />
          </div>
        </div>
      </div>

      <a-spin :spinning="goodAppsLoading">
        <div class="apps-grid">
          <AppCard
            v-for="app in goodApps"
            :key="app.id"
            :app="app"
            :show-author="true"
            @click="viewAppDetail"
            @detail="viewAppDetail"
            @view-work="viewWork"
          />
        </div>

        <EmptyState
          v-if="goodApps.length === 0 && !goodAppsLoading"
          description="暂无精选应用"
        />

        <a-pagination
          v-if="goodAppsPagination.total > 0"
          :current="goodAppsPagination.pageNum"
          :page-size="goodAppsPagination.pageSize"
          :total="goodAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="false"
          @change="handleGoodAppsPageChange"
          class="pagination"
        />
      </a-spin>
    </div>
  </div>
</template>

<style scoped>
.home-page {
  min-height: 100vh;
}

/* 英雄区域样式 */
.hero-section {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  padding: 100px 0 140px;
  text-align: center;
  margin: -24px -24px 40px -24px;
  overflow: hidden;
}

.hero-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 50%, rgba(120, 160, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 120, 160, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(160, 255, 120, 0.1) 0%, transparent 50%);
  animation: floating 6s ease-in-out infinite;
}

@keyframes floating {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.hero-content {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 40px;
  position: relative;
  z-index: 1;
}

.hero-title {
  font-size: 54px;
  font-weight: 800;
  margin-bottom: 20px;
  line-height: 1.1;
  letter-spacing: -1px;
}

.title-gradient {
  background: linear-gradient(135deg, #2196F3 0%, #21CBF3 50%, #45B7D1 100%);
  background-size: 200% 200%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: gradientShift 3s ease-in-out infinite;
}

@keyframes gradientShift {
  0%, 100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

.title-accent {
  margin: 0 16px;
  display: inline-block;
  font-size: 48px;
  animation: sparkle 2s ease-in-out infinite;
}

@keyframes sparkle {
  0%, 100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
  50% {
    transform: scale(1.2) rotate(180deg);
    opacity: 0.8;
  }
}

.hero-subtitle {
  font-size: 22px;
  margin-bottom: 60px;
  color: #4a5568;
  font-weight: 400;
  line-height: 1.5;
}

/* 聊天输入区域 */
.chat-input-section {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.chat-container {
  background: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  padding: 20px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(20px);
  margin-bottom: 32px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-container:hover {
  transform: translateY(-2px);
  box-shadow:
    0 12px 40px rgba(0, 0, 0, 0.12),
    0 4px 12px rgba(0, 0, 0, 0.06);
  border-color: rgba(0, 0, 0, 0.08);
}

.chat-container:focus-within {
  transform: translateY(-1px);
  box-shadow:
    0 16px 48px rgba(0, 0, 0, 0.15),
    0 6px 16px rgba(0, 0, 0, 0.08);
  border-color: rgba(24, 144, 255, 0.2);
}

.chat-textarea {
  margin-bottom: 16px;
}

:deep(.chat-textarea .ant-input) {
  font-size: 16px;
  border: none;
  background: transparent;
  padding: 0;
  color: #1f2937;
  font-weight: 400;
  line-height: 1.6;
  resize: none;
}

:deep(.chat-textarea .ant-input:focus) {
  border: none;
  box-shadow: none;
  outline: none;
}

:deep(.chat-textarea .ant-input::placeholder) {
  color: #9ca3af;
  font-weight: 400;
  font-size: 16px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  height: 36px;
  padding: 0 12px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(107, 114, 128, 0.08);
  color: #374151;
}

.upload-btn:hover {
  background: rgba(59, 130, 246, 0.08);
  color: #3b82f6;
}

.optimize-btn:hover {
  background: rgba(245, 158, 11, 0.08);
  color: #f59e0b;
}

.send-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background: #1f2937;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.send-button:hover {
  background: #111827;
  transform: scale(1.05);
}

.send-button:active {
  transform: scale(0.95);
}

.send-button:disabled {
  background: #e5e7eb;
  color: #9ca3af;
  cursor: not-allowed;
  transform: none;
}

/* 示例提示 */
.example-prompts {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 12px;
}

.example-label {
  font-size: 14px;
  color: #718096;
  margin-right: 8px;
  font-weight: 500;
}

.example-tag {
  cursor: pointer;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  background: white;
  color: #4a5568;
  padding: 6px 16px;
  font-size: 14px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.example-tag:hover {
  border-color: #2196F3;
  background: #f7fafc;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.15);
}

/* 功能提示样式 */
/* 分类标签页样式 */
.category-tabs {
  margin: 24px 0;
  border-bottom: 1px solid #e8e9ea;
}

.tabs-container {
  display: flex;
  gap: 0;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.tabs-container::-webkit-scrollbar {
  display: none;
}

.tab-item {
  padding: 12px 24px;
  cursor: pointer;
  color: #666;
  font-weight: 500;
  border-bottom: 3px solid transparent;
  white-space: nowrap;
  transition: all 0.3s ease;
  position: relative;
  background: transparent;
}

.tab-item:hover {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.05);
}

.tab-item.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  background: rgba(24, 144, 255, 0.08);
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -3px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background: #1890ff;
  border-radius: 1.5px;
}

.tab-item.loading {
  pointer-events: none;
  opacity: 0.7;
}

.tab-item .ant-spin {
  font-size: 12px;
}

.feature-tips {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 24px;
  flex-wrap: wrap;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  color: #6b7280;
  font-size: 13px;
  transition: all 0.2s ease;
}

.tip-item:hover {
  background: rgba(255, 255, 255, 0.95);
  color: #4b5563;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.tip-icon {
  font-size: 12px;
  color: #9ca3af;
}

/* 加载状态样式优化 */
.action-btn[loading] {
  pointer-events: none;
  opacity: 0.7;
}

/* 区域样式 */
.section {
  margin-bottom: 60px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

/* 应用网格 */
.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}




.author-name {
  font-size: 14px;
  color: #595959;
}

.app-actions {
  display: flex;
  gap: 8px;
}

.app-actions .ant-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.app-actions .ant-btn-primary {
  background: linear-gradient(135deg, #2196F3 0%, #21CBF3 100%);
  border: none;
}

.app-actions .ant-btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.4);
}

.app-actions .ant-btn:not(.ant-btn-primary) {
  border-color: #e2e8f0;
  color: #4a5568;
}

.app-actions .ant-btn:not(.ant-btn-primary):hover {
  border-color: #2196F3;
  color: #2196F3;
  transform: translateY(-1px);
}


/* 分页 */
.pagination {
  text-align: center;
  margin-top: 32px;
}

/* 大屏幕优化 */
@media (min-width: 1400px) {
  .hero-content {
    max-width: 1200px;
    padding: 0 60px;
  }

  .chat-input-section {
    max-width: 1000px;
    padding: 0 40px;
  }

  .apps-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 32px;
  }
}

/* 中等屏幕优化 */
@media (min-width: 1024px) and (max-width: 1399px) {
  .apps-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 28px;
  }
}

/* 小屏幕优化 */
@media (max-width: 768px) {
  .hero-section {
    padding: 80px 0 100px;
  }

  .hero-title {
    font-size: 40px;
  }

  .hero-subtitle {
    font-size: 18px;
    margin-bottom: 40px;
  }

  .chat-container {
    border-radius: 12px;
    padding: 16px;
  }

  .input-actions {
    flex-direction: column;
    gap: 12px;
  }

  .action-buttons {
    justify-content: flex-start;
    width: 100%;
  }

  .send-button {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    align-self: flex-end;
  }

  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .apps-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
  }

  .hero-content {
    padding: 0 30px;
  }

  .chat-input-section {
    padding: 0 20px;
  }

  .example-prompts {
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  .example-label {
    margin-bottom: 8px;
  }

  .feature-tips {
    flex-direction: column;
    gap: 12px;
  }

  .tip-item {
    font-size: 12px;
    padding: 6px 12px;
  }

  /* 分类标签页移动端适配 */
  .category-tabs {
    margin: 16px -20px 20px -20px;
    padding: 0 20px;
  }

  .tab-item {
    padding: 10px 16px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .hero-content {
    padding: 0 16px;
  }

  .hero-title {
    font-size: 32px;
  }

  .title-accent {
    font-size: 32px;
  }

  .apps-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .chat-input-section {
    padding: 0 8px;
  }
}
</style>
